<?php
$conn =mysql_connect('localhost','root','');
if(!$conn){
    die('Count not connect ...');
}else{
    mysql_select_db('test',$conn) || die('Count not select db test...');
    mysql_query("set names 'utf8'",$conn);
}

if(!empty($_POST)){
    //添加用户信息到数据表
    foreach ($_POST as $key => $value) {
        if(empty($value) && $key!=='sex'){
            header("Content-Type: text/html; charset=utf-8");
            header("refresh:1;url=register.php");
            exit('请填写完整');
        }
    }
    //验证数据合法性
    $name = trim($_POST['uname']);
    if(!is_string($name)){
        header("Content-Type: text/html; charset=utf-8");
        header("refresh:1;url=register.php");
        exit('用户名不合法');
    }
    if($_POST['pwd']!== $_POST['conpwd']){
        header("Content-Type: text/html; charset=utf-8");
        header("refresh:1;url=register.php");
        exit('两次密码输入不一致');
    }
    $pwd = md5($_POST['pwd']);
    $sex = is_int($_POST['sex']) ? $_POST['sex'] : 0;
    $phone = isPhone($_POST['phone']) ? $_POST['sex'] : '';
    $email = isEmail($_POST['email']) ? $_POST['email'] : '';
    $address = trim(addslashes($_POST['address']));
    $date = date('Y-m-d H:i:s');
    $sql = mysql_query("insert into vote_users(`name`,`password`,`sex`,`phone`,`email`,`address`,`register_time`)
        values('$name','$pwd',$sex,'$phone','$email','$address','$date')");
    if(!$sql){
        exit('注册失败');
    }
    header("Content-Type: text/html; charset=utf-8");
    header("refresh:1;url=register.php");
    exit('注册成功');
    print_r($_POST);exit;
}
include 'register.html';

function isPhone($val)  
{  
    //eg: xxx-xxxxxxxx-xxx | xxxx-xxxxxxx-xxx ...  
    if(preg_match("/^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/",$val))  
        return true;  
    return false;  
}
function isEmail($val,$domain="")  
{  
    if(!$domain)  
    {  
        if( preg_match("/^[a-z0-9-_.]+@[\da-z][\.\w-]+\.[a-z]{2,4}$/i", $val) )  
        {  
            return true;  
        }  
        else  
            return false;  
    }  
    else  
    {  
        if( preg_match("/^[a-z0-9-_.]+@".$domain."$/i", $val) )  
        {  
            return true;  
        }  
        else  
            return false;  
    }  
}
function isName($val)  
{  
    if( preg_match("/^[\x80-\xffa-zA-Z0-9]{3,60}$/", $val) )//2008-7-24  
    {  
        return true;  
    }  
    return false;  
}
?>